package org.teemor.demo.netty.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import org.teemor.demo.netty.client.handler.ImClientHandler;
import org.teemor.demo.netty.client.handler.TimeClientHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author zhoulk
 * @date 2024/1/9 15:00
 * @desc
 */
public class ImClient {

    public static void main(String[] args) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline()
                            .addLast("frameDecoder", new LengthFieldBasedFrameDecoder(
                                    4 + 6 * 1024
                                    , 0, 4, 0, 4))
                            .addLast("frameEncoder", new LengthFieldPrepender(4))
                            .addLast(new ImClientHandler());
                }
            });
            ChannelFuture f = b.connect("139.198.169.193", 9903).sync();
            ByteBuf byteBuf = f.channel().alloc().buffer();
            byteBuf.writeBytes(new JSONObject().fluentPut("type", 0).fluentPut("dataContent",
                    new JSONObject().fluentPut("loginUserId", 400069).fluentPut("loginToken", "30ede7a651694c80bc3475bf98649dbc").toJSONString())
                    .toJSONString()
                    .getBytes(StandardCharsets.UTF_8));
            f.channel().writeAndFlush(byteBuf)
                    .addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) throws Exception {
                            System.out.println("complete");
                        }
                    })
            ;
            f.channel().closeFuture().sync();
        } catch (Exception e) {

        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
